# Copyright (c) 2012-4 Aaron Sun <hisycg@gmail.com>. All rights reserved.
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.

#!/usr/bin/perl
use warnings;
use strict;
use Tk;
use IO::Socket;

require Tk::ROText;
my $opt;
my $socket;


sub init_opt{
  $opt->{name} = $ARGV[0] || $ENV{USER} || 'Anonymous';
  my $hostname = `hostname`;chomp($hostname);
  $opt->{host} = $hostname;
  $opt->{serv} = 'localhost';
  $opt->{port} = 55555;
}

sub init_connection{
  # create the socket
  $socket = IO::Socket::INET->new(
        PeerAddr => $opt->{serv},
        PeerPort => $opt->{port},
        Proto    => 'tcp',
        );
  defined $socket or die "ERROR: Can't connect to port $opt->{port} on $opt->{serv}: $!\n";
  print "Connected to server ...\n";
  print $socket "#CLIENTINFO#USER:$opt->{name},HOST:$opt->{host}\n";
}

sub start_chat{
  my $mw  = new MainWindow;
  my $log = $mw->Scrolled('ROText',
            -scrollbars=>'ose',
            -height=> 15,
            -width=>60,
            -background => 'lightgreen',
            )->pack;

  my $txt = $mw->Entry(
            -background=>'white',
            )->pack(-fill=> 'x', -pady=> 5);

  $mw ->bind('<Any-Enter>' => sub { $txt->Tk::focus });
  $txt->bind('<Return>' => [\&broadcast, $socket]);

  $mw ->fileevent($socket, readable => sub {
                      my $line = <$socket>;
                        unless (defined $line) {
                        $mw->fileevent($socket => readable => '');
                        return;
                        }
          $log->insert(end => $line);
          $log->see('end');
    });
  MainLoop;
}

sub broadcast {
    my ($ent, $sock) = @_;
    my $text = $ent->get;
    $ent->delete(qw/0 end/);
    print $sock $text, "\n";
}

sub main{
  init_opt;
#   print Dumper($opt);
  init_connection;
  start_chat;
}

&main;